package com.bawei.library_net.convert;

import android.text.TextUtils;

import com.bawei.library_net.entity.ResponseEntity;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/19 15:45
 * @Description : CustomGsonResponseBodyConverter
 */
public class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private Type type;

    CustomGsonResponseBodyConverter(Gson gson,Type type, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String string = value.string();//json数据
        if(!TextUtils.isEmpty(string)){
            //TODO 1：第一次按照ResponseEntity.class解析
            ResponseEntity responseEntity = gson.fromJson(string, ResponseEntity.class);
            //TODO 2：判断code == -1 失败
            if(responseEntity != null && responseEntity.getCode() == -1){//==-1的时候由于data为""，解析的时候会报错当作异常处理,我们不需要当作异常
                //TODO 2-1：失败：返回第一步解析的responseEntity对象
                return (T)responseEntity;
            }else{
                //TODO 2-2：成功：按照type解析并返回responseEntity对象
                return gson.fromJson(string,type);//type = ResponseEntity<MutableList<VideoEntity>>
            }
        }
        return gson.fromJson(string,type);

    }
}

